<?php
namespace Addons\CustomQr\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper as QyHelper;
use Addons\Fission\Helper;
use Addons\Moments\Helper as Helpers;

use Addons\QyWechat\Services\QyWechatApi;
class CustomQr extends \BaseController
{
	public function index(){
		$wid = Session::get('wid');	
		$where["wid"] = $wid;
		$where["type"] = 1;
		$where["status"] = 1;
		$p = new \Pagination();	 
		if(\Request::get("title")){
			$where["title@~"] = \Request::get("title");
		}
		$res = $p->model_list((new Model("qy_customqr"))->where($where)->order('id desc'));
		foreach ($res as $key => $value) {
			$res[$key]->user = (new Model("qy_user_list"))->field("name")->find($value->user_id);
		}
		$this->assign("create_qrcode", Helpers::getInstance()->get_http_server_name()."/Addons/CustomQr/Admin/CustomQr/create_qrcode.html");
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("title", \Request::get("title"));
		$this->assign("res", $res);
		return $this->show();
	}

	public function list(){
		$wid = Session::get('wid');	
		$where["wid"] = $wid;
		$where["type"] = 2;
		$where["status"] = 1;
		$p = new \Pagination();	
		if(\Request::get("title")){
			$where["title@~"] = \Request::get("title");
		}
		$res = $p->model_list((new Model("qy_customqr"))->where($where)->order('id desc'));
		foreach ($res as $key => $value) {
			$res[$key]->user = (new Model("qy_user_list"))->field("name")->find($value->user_id);
		}
		$this->assign("create_qrcode", Helpers::getInstance()->get_http_server_name()."/Addons/CustomQr/Admin/CustomQr/create_qrcode.html");
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("title", \Request::get("title"));
		$this->assign("res", $res);
		return $this->show();
	}

	public function add_customqr(){
		$wid = Session::get('wid');	
		$gzh_list = (new Model('qy_gzh_token'))->where(['wid'=>$wid])->list_all_array();
		$id = \Request::get(1);
		if($id){
			$customqr = (new Model("qy_customqr"))->find($id);
		}else{
			$customqr = new Model("qy_customqr");
		}
		$h = QyHelper::getInstance();
		if(is_post()){
			setApi();
			if(!$_POST["checkUser"]){
				sendError("请选择使用人员");
			}
			if(!$id){
				$customqr->wid = $wid;
				$customqr->ctime = time();
			}else if($customqr->user_id != $_POST["checkUser"]){
				$QyWechatApi = QyWechatApi::getInstance();
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				$del = $etApp->contact_way->delete($customqr->config_id);
				if($del["errmsg"] != "ok"){
					sendError("操作失败");
				}
			}
			$customqr->user_id = $_POST["checkUser"];
			$customqr->welcome_text = json_encode($_POST["welcome_text"]);
			$customqr->auto_label = $_POST["auto_label"]?1:0;
			$customqr->is_welcome = $_POST["is_welcome"]?1:0;
			$checkLable = json_encode(explode(',',$_POST['checkLable']),320);
			$customqr->checkLable = $checkLable;
			$customqr->type = 1;
			$customqr->status = 1;
			$customqr->authorizer_appid = $_POST["authorizer_appid"];
			$customqr->xcx_appid = $_POST["xcx_appid"];
			$customqr->xcx_url = $_POST["xcx_url"];
			$customqr->title = $_POST["title"];
			$customqr->miniprogram_name = $_POST["miniprogram_name"];
			$customqr->miniprogram_appid = $_POST["miniprogram_appid"];
			$customqr->miniprogram_page = $_POST["miniprogram_page"];
			$customqr->miniprogram_title = $_POST["miniprogram_title"];
			$customqr->pic_image = $_POST["pic_image"];
			if($customqr->save()){
				$QyWechatApi = QyWechatApi::getInstance();
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				$user_list  = (new Model('qy_user_list'))->find(['id'=>$customqr->user_id]);
				$user_id[] = $user_list->userid;
				$state = 'qr_' . $customqr->id;//企业自定义的state参数，用于区分不同的添加渠道
				$config = [
				   'skip_verify' => true,//外部客户添加时是否无需验证
				   'state' => $state,
				   'user' => $user_id,
				];
				$createRes = $etApp->contact_way->create(1, 2, $config);
				$customqr->qr_code = $createRes["qr_code"];
				$customqr->config_id = $createRes["config_id"];
				$customqr->state = $state;
				for ($i=1; $i <= $_POST["part_time_counts"]; $i++) { 
				 	if($_POST["part_time_other_types".$i] == 1){
						continue;
					}else if($_POST["part_time_other_types".$i] == 2){
						$welcome["image"] = $_POST["image".$i];
					}else if($_POST["part_time_other_types".$i] == 3){
						$welcome["url"] = $_POST["link_url".$i];
						$welcome["title"] = $_POST["link_title".$i];
						$welcome["describe"] = $_POST["link_desc".$i];
						$welcome["picurl"] = $_POST["link_pic".$i];
					}else if($_POST["part_time_other_types".$i] == 4){
						$welcome["name"] = $_POST["miniprogram_name".$i];
						$welcome["appid"] = $_POST["miniprogram_appid".$i];
						$welcome["title"] = $_POST["miniprogram_title".$i];
						$welcome["page"] = $_POST["miniprogram_page".$i];
						$welcome["image"] = $_POST["miniprogram_pic".$i];
					}else if($_POST["part_time_other_types".$i] == 5){
						$welcome["red_id"] = $_POST["part_time_otype_reds".$i];
					}
					$welcome["type"] = $_POST["part_time_other_types".$i];
					$welcome_list[] = $welcome;
				}
				$customqr->welcome_list = json_encode($welcome_list,320);
				$customqr->save(); 
				sendSuccess("操作成功");
			}sendError("操作失败");
		}
		foreach ($gzh_list as $gzh_listk => $gzh_listv) {
			$gzh_list[$gzh_listk]["message"] = json_decode($gzh_listv["message"])->authorizer_info->nick_name;
		}
		$customqr->welcome_list = json_decode($customqr->welcome_list,1);
		$this->assign("gzh_list", $gzh_list);
		$this->assign("customqr", $customqr);
		$this->assign("h", $h);
		return $this->show();
	}

	public function select_tag(){
		$wid = Session::get('wid');
		$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		foreach ($etTagArr as $key => $value) {
			$count += count(json_decode($value['tags'],1));
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("count",$count);
		return $this->show();
	}

	public function select_user(){
		$wid = Session::get('wid');
		$where['wid'] = $wid;
		$where['status'] = 1; 
		$where['is_del@!='] = 1;
		$userList = (new Model('qy_user_list'))->where($where)->list_all_array();
		$this->assign("userList", $userList);
		$this->assign("count", count($userList));
		return $this->show();
	}

	public function create_qrcode(){
		$id = \Request::get("id");
		$severname = Helper::getInstance()->get_http_server_name().'/Addons/CustomQr/H5/CustomQr/index.html?';
		\QRcode::png($severname."id={$id}",false,"L",4);
		exit;
	}

	public function download_qrcode(){
		$id = \Request::get(1);
		$customqr = (new Model("qy_customqr"))->find($id);
		$url = Helpers::getInstance()->get_http_server_name()."/Addons/CustomQr/Admin/CustomQr/create_qrcode.html?id={$id}";
		header('Content-Disposition:attachment;filename='.$customqr->title.'.png');
		header('Content-Length:' . filesize($url));
		//读取文件并写入到输出缓冲
		readfile($url);
	}

	public function del_customqr(){
		setApi();
		$id = $_POST["id"];
		$wid = Session::get('wid');
		$customqr = (new Model("qy_customqr"))->find($id);
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$del = $etApp->contact_way->delete($customqr->config_id);
		$customqr->status = 2;
		if($del["errmsg"] == "ok" && $customqr->save()){
			sendSuccess("操作成功");
		}sendError("删除失败");
	}

	public function add_bg(){
		setApi();
		$wid = Session::get('wid');
		$bg = (new Model('qy_customqr_bg'))->find(["wid"=>$wid]);
		if(is_post()){
			if(!$bg->id){
				$bg->wid = $wid;
			}
			$bg->background = $_POST["background"];
			$bg->add_text = $_POST["add_text"];
			$bg->text = $_POST["text"];
			if($bg->save()){
				sendSuccess("操作成功");
			}sendError("操作失败");
		}
		$this->assign("bg",$bg);
		return $this->show();
	}



	//下面是公众号的

	public function add_customqrs(){
		$wid = Session::get('wid');	
		$id = \Request::get(1);
		$h = QyHelper::getInstance();
		if($id){
			$customqr = (new Model("qy_customqr"))->find($id);
		}else{
			$customqr = new Model("qy_customqr");
		}
		if(is_post()){
			setApi();
			if(!$_POST["checkUser"]){
				sendError("请选择使用人员");
			}
			if(!$id){
				$customqr->wid = $wid;
				$customqr->ctime = time();
			}else if($customqr->user_id != $_POST["checkUser"]){
				$QyWechatApi = QyWechatApi::getInstance();
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				$del = $etApp->contact_way->delete($customqr->config_id);
				if($del["errmsg"] != "ok"){
					sendError("操作失败");
				}
			}
			$customqr->title = $_POST["title"];
			$customqr->user_id = $_POST["checkUser"];
			$customqr->type = 2;
			$customqr->status = 1;
			$customqr->url = $_POST["url"];
			$customqr->text_title = $_POST["text_title"];
			$customqr->text_url = $_POST["text_url"];
			$customqr->text_content = $_POST["text_content"];
			$customqr->text_image = $_POST["text_image"];
			$customqr->welcome_text = json_encode($_POST["welcome_text"]);
			$customqr->auto_label = $_POST["auto_label"]?1:0;
			$customqr->is_welcome = $_POST["is_welcome"]?1:0;
			$checkLable = json_encode(explode(',',$_POST['checkLable']),320);
			$customqr->checkLable = $checkLable;
			if($customqr->save()){ 
				$QyWechatApi = QyWechatApi::getInstance();
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				$user_list  = (new Model('qy_user_list'))->find(['id'=>$customqr->user_id]);
				$user_id[] = $user_list->userid;
				$state = 'qr_' . $customqr->id;//企业自定义的state参数，用于区分不同的添加渠道
				$config = [
				   'skip_verify' => true,//外部客户添加时是否无需验证
				   'state' => $state,
				   'user' => $user_id,
				];
				$createRes = $etApp->contact_way->create(1, 2, $config);
				$customqr->qr_code = $createRes["qr_code"];
				$customqr->config_id = $createRes["config_id"];
				$customqr->state = $state;
				for ($i=1; $i <= $_POST["part_time_counts"]; $i++) { 
				 	if($_POST["part_time_other_types".$i] == 1){
						continue;
					}else if($_POST["part_time_other_types".$i] == 2){
						$welcome["image"] = $_POST["image".$i];
					}else if($_POST["part_time_other_types".$i] == 3){
						$welcome["url"] = $_POST["link_url".$i];
						$welcome["title"] = $_POST["link_title".$i];
						$welcome["describe"] = $_POST["link_desc".$i];
						$welcome["picurl"] = $_POST["link_pic".$i];
					}else if($_POST["part_time_other_types".$i] == 4){
						$welcome["name"] = $_POST["miniprogram_name".$i];
						$welcome["appid"] = $_POST["miniprogram_appid".$i];
						$welcome["title"] = $_POST["miniprogram_title".$i];
						$welcome["page"] = $_POST["miniprogram_page".$i];
						$welcome["image"] = $_POST["miniprogram_pic".$i];
					}else if($_POST["part_time_other_types".$i] == 5){
						$welcome["red_id"] = $_POST["part_time_otype_reds".$i];
					}
					$welcome["type"] = $_POST["part_time_other_types".$i];
					$welcome_list[] = $welcome;
				}
				$customqr->welcome_list = json_encode($welcome_list,320);
				$customqr->save();
				sendSuccess("操作成功");
			}sendError("操作失败");
		}
		$customqr->welcome_list = json_decode($customqr->welcome_list,1);
		$this->assign("h",$h);
		$this->assign("customqr",$customqr);
		return $this->show();
	}

}